package com.ruoyi.framework.interceptor;


import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.GeneralEntity;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Properties;

/**
 * @Description: mybatis拦截器
 * @Author: LJ
 * @Date: 2022/1/24 14:19
 * @version:
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class SqlInterceptor implements Interceptor {

    @Override
    public Object intercept(final Invocation invocation) throws Throwable {
        final Object[] args = invocation.getArgs();

        // update方法有两个参数，参见Executor类中的update()方法。
        final Object arg0 = args[0];
        final Object arg1 = args[1];

        // 第一个参数处理。根据它判断是否给“操作属性”赋值。
        if (arg0 instanceof MappedStatement) {// 如果是第一个参数 MappedStatement
            final MappedStatement mappedStatement = (MappedStatement) arg0;
            final SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            if (sqlCommandType == SqlCommandType.INSERT || sqlCommandType == SqlCommandType.UPDATE) {
                // 如果是“增加”或“更新”操作，则继续进行默认操作信息赋值。否则，则退出
                if (arg1 instanceof Map) {// 如果是map，有两种情况：（1）使用@Param多参数传入，由Mybatis包装成map。（2）原始传入Map
                    final Map map = (Map) arg1;
                    for (final Object obj : map.values()) {
                        setProperty(obj, sqlCommandType);
                    }
                } else {// 原始参数传入
                    setProperty(arg1, sqlCommandType);
                }
            }
        }

        return invocation.proceed();

    }

    /**
     * 为对象的操作属性赋值
     *
     * @param obj
     */
    private void setProperty(final Object obj, final SqlCommandType sqlCommandType) {
        if (!(obj instanceof GeneralEntity)) {
            return;
        }
        try {
            //从用户上下文获取当前登录用户
            final Long userId = SecurityUtils.getDefaultUserId();
            if (sqlCommandType == SqlCommandType.INSERT) {
                // TODO: 2022/2/14 自动使用自增
                //BeanUtil.setProperty(obj, "id", SnowflakeWorker.nextId()); 是否使用自增而定
                if (ToolUtil.isNotEmpty(userId)) BeanUtil.setProperty(obj, "createBy", userId);
                BeanUtil.setProperty(obj, "createTime", LocalDateTime.now());
                if (ToolUtil.isNotEmpty(userId)) BeanUtil.setProperty(obj, "updateBy", userId);
                BeanUtil.setProperty(obj, "updateTime", LocalDateTime.now());
                BeanUtil.setProperty(obj, "isDelete", false);
            } else {
                if (ToolUtil.isNotEmpty(userId)) BeanUtil.setProperty(obj, "updateBy", userId);
                BeanUtil.setProperty(obj, "updateTime", LocalDateTime.now());
            }
        } catch (final Exception e) {
            log.debug("赋予默认创建/修改人失败：{}", e.getMessage(), e);
        }
    }

    @Override
    public Object plugin(final Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(final Properties properties) {

    }

}
